// components/bindform/bindform.ts
import api from "../../utils/api"
import animationHelper from '../..//utils/animation';
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    code: String,
    add: Boolean,//是否为添加
  },

  /**
   * 组件的初始数据
   */
  data: {
    radio: 'MALE' as string,//male男性，female女性
    years: [] as number[],
    months: [] as number[],
    days: [] as number[],
    year: 0 as number,
    month: 1 as number,
    day: 1 as number,
    birthday: '' as string,//展示的日期
    value: [] as Array<number>,
    testPickerVal: [] as Array<number>,
    showDate: false as boolean,//是否展示日期
    animation: null as WechatMiniprogram.Animation | null,
    animationData: {} as any,
    testList: [] as TestingItemModel[],//检测项目列表
    showTest: false as boolean,//展示检测项目弹窗,
    testVal: {} as TestingItemModel,//选择的值
    testTempVal: {} as TestingItemModel,//临时值
    name: '' as string,//姓名
    phone: '' as string,
    notes: '' as string,
    sampleType: {} as SampleTypeModel,//样本类型
    sampleTypeTemp: {} as ExtraFieldModel,//临时样本类型
    typePickerValue: [] as Array<number>,
    showTips: false as boolean,//是否展示知情同意书
    showSampleType: false as boolean,//展示样本类型
    canClose: true as boolean,//是否可以关闭picker
    aboutInfo: '' as string,//知情同意书
    extraFields: [] as ExtraFieldModel[],//备注字段的个数
    remark:'' as string,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    changeRadio(e: any): void {
      this.setData({
        radio: e.currentTarget.dataset.type
      })
    },
    getDaysInMonth(year: number, month: number) {
      // 创建一个日期对象，设置为指定年月的第一天
      const date = new Date(year, month, 1);

      // 将日期设置为下个月的第一天，然后减去1天，得到的就是本月的最后一天
      date.setDate(1); // 重新设置为1，以防之前有变动
      date.setMonth(date.getMonth() + 1);
      date.setDate(0); // 设置为下个月的最后一天

      // 使用getDate()方法获取这个日期是下个月的第几天，即本月的天数
      return date.getDate();
    },
    bindChange(e: any): void {
      const val = e.detail.value;
      this.setData({
        year: this.data.years[val[0]],
        month: this.data.months[val[1]],
        day: this.data.days[val[2]],
      })
    },
    testChange(e: any): void {
      const val = e.detail.value;
      this.setData({
        testTempVal: this.data.testList[val[0]]
      })
    },
    // 展示riqi弹窗
    showDialog(): void {
      this.showAnimation("showDate");
    },
    // 展示检测项目
    showTestDialog(): void {
      this.showAnimation("showTest");
    },
    closeTestDialog(): void {
      this.closeAnimation('showTest');
    },
    // 关闭弹窗
    closeDialog(): void {
      this.closeAnimation('showDate');
    },
    // 点击确定
    confirm(): void {
      if (!this.data.canClose) {
        wx.showToast({
          title: "请稍后点击",
          icon: "error"
        })
        return
      }
      this.setData({
        birthday: this.data.year + '-' + this.data.month.toString().padStart(2, '0') + '-' + this.data.day.toString().padStart(2, '0'),
        value: [this.data.year - 1900, this.data.month - 1, this.data.day - 1]
      })
      this.closeDialog();
    },
    confirmTest(): void {
      if (!this.data.canClose) {
        wx.showToast({
          title: "请稍后点击",
          icon: "error"
        })
        return
      }
      const index = this.data.testList.findIndex(item => item.id === this.data.testTempVal.id);
      const extraFields = this.data.testTempVal.extraFields
      if (extraFields) {
        extraFields.forEach(item => {
          item.value = ""
        })
      }
      this.setData({
        testVal: this.data.testTempVal,
        testPickerVal: [index],
        // 将样本类型置为第一个
        typePickerValue: [0],
        // 设置额外字段
        extraFields,
        sampleType: this.data.testTempVal.sampleType
      })
      // if (this.data.testTempVal.sampleTypes) {
      //   this.setData({
      //     sampleTypeTemp: this.data.testTempVal.sampleTypes[0]
      //   })
      // }
      this.closeTestDialog();
    },
    showAnimation(showType: string, height: number = 450): void {
      const animation = animationHelper.createAnimation(500, 'ease');
      this.setData({ animation: animation });
      animationHelper.showAnimation(animation, height, this.setData.bind(this), showType);
    },
    closeAnimation(showType: string, height: number = 450): void {
      const animation = this.data.animation;
      animationHelper.closeAnimation(animation, height, this.setData.bind(this), showType);
    },
    // 姓名
    handleName(e: any): void {
      this.setData({
        name: e.detail.value
      })
    },
    // 电话
    handlePhone(e: any): void {
      this.setData({
        phone: e.detail.value
      })
    },
    // 备注
    handleNotes(e: any): void {
      const { extraFields } = this.data
      const id = e.currentTarget.dataset.id
      const value = e.detail.value
      const index = extraFields.findIndex(item => {
        return item.id == id
      })
      extraFields[index].value = value
      this.setData({
        extraFields
      })
    },
    handleRemark(e:any): void {
      const remark = e.detail.value
      this.setData({
        remark
      })
    },
    // 样本类型
    // handleSampleType(): void {
    //   if (Object.keys(this.data.testVal).length) {
    //     if(this.data.testVal.sampleTypes && !this.data.testVal.sampleTypes.length ) {
    //       wx.showToast({
    //         title:"不存在样本类型",
    //         icon:"error"
    //       })
    //       return
    //     }
    //     this.showAnimation("showSampleType")
    //   } else {
    //     wx.showToast({
    //       title: "请先选择检测项目",
    //       icon: "none"
    //     })
    //   }
    // },
    // 展示知情同意书
    showTips(): void {
      const { testVal, name, phone, radio, birthday, code, sampleType, notes, extraFields } = this.data
      if (!code || !name || !radio || !phone || !Object.keys(sampleType).length || !Object.keys(testVal).length) {
        wx.showToast({
          title: "存在为空的项",
          icon: "error"
        })
        return
      }
      // 如果为添加
      if (this.data.add) {
        // 参数整理
        const extraDataList: ExtraData[] = extraFields.map(item => {
          return {
            id: item.id,
            value: item.value
          }
        })
        const params: BindSampleParam = {
          name: name,
          phone: phone,
          gender: radio,
          birthday: birthday,
          testingItemId: testVal.id,
          testingItemName: testVal.name,
          code: code,
          extraDataList,
          sampleTypeId: sampleType.id,
          sampleTypeName: sampleType.name
        }
        const pages = getCurrentPages();
        const prePage = pages[pages.length - 2];
        prePage.data.excelResult.push(params)
        prePage.setData({
          excelResult: prePage.data.excelResult
        })
        console.log('naviback');
        wx.navigateBack()
      } else {
        this.getInformedConsentForm()
        this.showAnimation("showTips", 454)
      }
    },
    closeTips(): void {
      this.closeAnimation("showTips", 454)
    },
    // 绑定样本
    bindSample(): void {
      const { testVal, notes, name, phone, radio, birthday, code, sampleType, extraFields, remark } = this.data
      // 参数整理
      const extraDataList: ExtraData[] = extraFields.map(item => {
        return {
          id: item.id,
          value: item.value
        }
      })
      const params: BindSampleParam = {
        name: name,
        phone: phone,
        gender: radio,
        birthday: birthday,
        testingItemId: testVal.id,
        code: code,
        extraDataList,
        sampleTypeId: sampleType.id,
        remark
      }
      console.log("绑定样本对应参数 ：" + JSON.stringify(params))
      api.sampleBind.bindSample(params).then(res => {
        if (res.data.code == "000") {
          this.triggerEvent("changeType", { type: 2 })
        } else {
          wx.showToast({
            title: res.data.message as string,
            icon: 'error',
            duration: 2000
          })
          console.error(res.data.message);
        }
      })
    },
    // 关闭样本类型弹窗
    closeSampleType(): void {
      this.closeAnimation("showSampleType")
    },
    // 确认选择样本类型
    // confirmType(): void {
    //   if (!this.data.canClose) {
    //     wx.showToast({
    //       title: "请稍后点击",
    //       icon: "error"
    //     })
    //     return
    //   }
    //   let index
    //   if (this.data.testVal.sampleTypes) {
    //     index = this.data.testVal.sampleTypes.findIndex(item => item.name === this.data.sampleTypeTemp.name);
    //   }
    //   this.setData({
    //     sampleType: this.data.sampleTypeTemp,
    //     typePickerValue: [index as number]
    //   })
    //   this.closeSampleType();
    // },
    // 开始选择
    pickerStart(): void {
      this.setData({
        canClose: false
      })
    },
    // 更改类型
    // typeChange(e: any): void {
    //   const val = e.detail.value;
    //   console.log(val)
    //   if (this.data.testVal.sampleTypes) {
    //     this.setData({
    //       sampleTypeTemp: this.data.testVal.sampleTypes[val[0]]
    //     })
    //   }
    // },
    pickerEnd(): void {
      this.setData({
        canClose: true
      })
    },
    // 获取知情同意书
    getInformedConsentForm(): void {
      api.texts.getInformedConsentForm().then(res => {
        if (res.data.code == "000") {
          this.setData({
            aboutInfo: res.data.data
          })
        } else {
          wx.showToast({
            title: res.data.message as string,
            icon: "error"
          })
        }
      })
    }
  },
  attached() {
    // 获取检测项目
    api.sampleBind.getTestingItemList().then(res => {
      if (res.data.code == "000") {
        this.setData({
          testList: res.data.data,
          testTempVal: res.data.data![0]
        })
      } else {
        wx.showToast({
          title: res.data.message as string,
          icon: 'error',
          duration: 2000
        })
        console.error(res.data.message);
      }
    })
    const date = new Date()
    const years = []
    const months = []
    const days = []
    for (let i = 1900; i <= date.getFullYear(); i++) {
      years.push(i)
    }
    for (let i = 1; i <= 12; i++) {
      months.push(i)
    }
    for (let i = 1; i <= 31; i++) {
      days.push(i)
    }
    this.setData({
      years,
      months,
      days,
      year: date.getFullYear(),
    })
    setTimeout(() => {
      this.setData({
        value: [9999, 1, 1],
        testPickerVal: [0],
      })
    })
  }
})